//
//  MLoginService.m
//  ios-test
//
//  Created by Apple -11 on 15/10/27.
//  Copyright (c) 2015年 Apple -11. All rights reserved.
//

#import "MLoginService.h"

#define REGISTER_URL [NSString stringWithFormat:@"%@%@",BASE_SERVER_URL,@"/api/User"]

#define LOGIN_URL [NSString stringWithFormat:@"%@",@"/api/User"]
//@"%@?username=%@&password=%@"


@implementation MLoginService
+(id)sharedClient
{
    static dispatch_once_t pred;
    static MLoginService *shared_instance=nil;
    dispatch_once(&pred, ^{
        shared_instance=[[self alloc] init];
        shared_instance.client=[self sharedHTTPClient];
    });
    return  shared_instance;
}
-(void)getProductListWithUsername:(NSString *)username password:(NSString *)password completion:(getLoignListCompletionHandler)success failure:(getLoginErrorHandler)failure{
    NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
    if (username) {
        [params setObject:username forKey:@"username"];
    }
    if(password){
        [params setObject:password forKey:@"password"];
    }
    NSString *path=[NSString stringWithFormat:@"%@?username=%@&password=%@",REGISTER_URL,username,password];
    
    [self.client postPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (operation.response.statusCode==200) {
            //success(@"注册成功");
            success(params);
        }else{
            failure(@"账号或密码错误");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(@"暂时访问不到，请稍后重试");
    }];
}
-(void)getLoginListWithUsername:(NSString *)username password:(NSString *)password completion:(loignListCompletionHandler)success failure:(loginErrorHandler)failure{
    
    NSMutableDictionary *params=[[NSMutableDictionary alloc]initWithObjectsAndKeys:username,@"username",password,@"password",nil];
    
    NSString *path=[NSString stringWithFormat:@"%@?username=%@&password=%@",LOGIN_URL,username,password];
    
    [self.client getPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id JSON =((AFJSONRequestOperation *)operation).responseJSON;
        if (!JSON) {
            failure(@"error");
            return ;
        }
        NSLog(@"%@",JSON);
        NSDictionary *dic=JSON;
        MLoginModel *model=[[[MLoginModel alloc]init] getLoginResultWithDictionaryJSON:dic];
        success(model);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(@"暂时访问不到，请稍后重试");
    }];
}
@end
